<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片查看器</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body, html {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        .container-fluid {
            height: calc(100% - 42px); /* 减去工具栏高度 */
            padding: 0;
        }

        .main-row {
            height: 100%;
            margin: 0;
            flex-wrap: nowrap;
        }

        .image-viewer-col {
            height: 100%;
            padding: 0;
            transition: width 0.3s ease;
            flex: 1;
            min-width: 0;
        }

        .image-viewer {
            height: 100%;
            border: 1px solid #ddd;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }

        .image-container {
            flex: 1;
            border: 1px solid #eee;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            position: relative;
        }

        .image-container img {
            max-width: none;
            max-height: none;
            transform-origin: center center;
            cursor: grab;
            user-select: none;
            position: relative;
        }

        .image-container img.with-animation {
            transition: transform 0.2s ease-out;
        }

        .image-container img.dragging {
            cursor: grabbing;
            transition: none;
        }

        .info-panel-col {
            height: 100%;
            padding: 0;
            transition: none;
            position: relative;
            width: 400px;
            flex: 0 0 auto;
            max-width: 800px;
        }

        /* 拖拽条样式 */
        .resize-handle {
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            background-color: transparent;
            cursor: col-resize;
            z-index: 1001;
            transition: background-color 0.2s;
        }

        .resize-handle:hover,
        .resize-handle.dragging {
            background-color: #0d6efd;
        }

        .method-panel {
            height: 100%;
            border: 1px solid #ddd;
            border-left: none;
            padding: 15px;
            position: relative;
            display: flex;
            flex-direction: column;
        }

        .toggle-panel-btn {
            position: absolute;
            right: 15px;
            top: 15px;
            z-index: 1000;
        }

        .navigation-buttons {
            text-align: center;
            margin-top: 20px;
        }

        .navigation-buttons .btn {
            margin: 0 5px;
            min-width: 40px;
        }

        .navigation-buttons .btn:first-child {
            margin-right: 5px;
        }

        .expand-panel-btn {
            position: fixed;
            right: 15px;
            top: 15px;
            z-index: 1000;
            display: none;  /* 初始状态隐藏 */
        }

        /* 可选：鼠标悬停时稍微放大按钮 */
        .expand-panel-btn:hover {
            transform: scale(1.1);
            transition: transform 0.2s;
        }

        .zoom-controls {
            text-align: center;
            margin: 10px 0;
        }

        .zoom-controls .btn {
            margin: 0 5px;
        }

        .zoom-level {
            display: inline-block;
            margin: 0 10px;
            min-width: 60px;
        }

        .connection-status {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background-color: #dc3545;
            color: white;
            text-align: center;
            padding: 8px;
            font-weight: bold;
            z-index: 2000;
            display: none;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .connection-status.show {
            display: block;
            opacity: 1;
        }

        /* 下载按钮样式 */
        .download-btn {
            opacity: 0.7;
            transition: opacity 0.2s;
        }

        .download-btn:hover {
            opacity: 1;
        }

        #customMessage {
            flex: 1;
            overflow-y: auto;
            margin-top: 10px;
            padding: 10px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        /* 结果表格。用在 Python 代码里 */
        .result-table {
            text-align: center;
            width: 100%;
            border-collapse: collapse;
            border: 1px solid #ddd;
        }

        .result-table td {
            border: 1px solid #ddd;
            padding: 5px;
        }

        .toolbar {
            background-color: #f8f9fa;
            padding: 6px;
            text-align: center;
            border-bottom: 1px solid #ddd;
            height: 42px; /* 减小工具栏高度 */
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toolbar .btn {
            margin: 0 5px;
            padding: 3px 10px;
            font-size: 0.875rem;
        }

        .toolbar .btn i {
            font-size: 0.875rem;
            margin-right: 4px;
        }
    </style>
</head>
<body>
    <!-- 工具栏 -->
    <div class="toolbar">
        <button class="btn btn-outline-primary" id="openLocalBtn">
            <i class="bi bi-folder2-open"></i> 打开
        </button>
        <button class="btn btn-outline-danger" id="clearBtn">
            <i class="bi bi-trash"></i> 清除记录
        </button>
    </div>

    <!-- 添加连接状态提示 -->
    <div class="connection-status" id="connectionStatus">
        WebSocket 连接已断开，正在尝试重新连接...
    </div>

    <!-- 添加展开按钮 -->
    <button class="btn btn-sm btn-secondary expand-panel-btn" id="expandPanel">
        <i class="bi bi-layout-sidebar"></i>
    </button>

    <div class="container-fluid">
        <div class="row main-row">
            <div class="col image-viewer-col" id="imageViewerCol">
                <div class="image-viewer">
                    <div class="image-container" id="imageViewer">
                        <!-- 图片将在这里显示 -->
                    </div>
                    <div class="zoom-controls">
                        <button class="btn btn-sm btn-outline-secondary" id="zoomOutBtn" alt="缩小">
                            <i class="bi bi-zoom-out"></i>
                        </button>
                        <span class="zoom-level" id="zoomLevel">100%</span>
                        <button class="btn btn-sm btn-outline-secondary" id="zoomInBtn" alt="放大">
                            <i class="bi bi-zoom-in"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" id="resetZoomBtn" alt="重置缩放">
                            <i class="bi bi-arrow-counterclockwise"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" id="downloadBtn" alt="下载图片">
                            <i class="bi bi-download"></i>
                        </button>
                        <div class="form-check form-check-inline ms-2">
                            <input class="form-check-input" type="checkbox" id="lockViewCheckbox">
                            <label class="form-check-label" for="lockViewCheckbox">锁定视图</label>
                        </div>
                        <div class="image-pagination ms-2 d-inline-block">
                            <button class="btn btn-sm btn-outline-secondary" id="prevImageBtn" disabled>
                                <i class="bi bi-arrow-left-short"></i>
                            </button>
                            <span id="imagePageCount" class="mx-2">1/1</span>
                            <button class="btn btn-sm btn-outline-secondary" id="nextImageBtn" disabled>
                                <i class="bi bi-arrow-right-short"></i>
                            </button>
                        </div>
                    </div>
                    <div class="slider-container mb-2">
                        <input type="range" class="form-range" id="pageSlider" value="0" min="0" max="0">
                    </div>
                    <div class="navigation-buttons">
                        <button class="btn btn-sm btn-outline-secondary" id="firstBtn" alt="第一张">
                            <i class="bi bi-chevron-bar-left"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" id="prevBtn" alt="上一张">
                            <i class="bi bi-chevron-left"></i>
                        </button>
                        <span id="funcCount" style="margin: 0 10px">0/0</span>
                        <button class="btn btn-sm btn-outline-secondary" id="nextBtn" alt="下一张">
                            <i class="bi bi-chevron-right"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" id="lastBtn" alt="最后一张">
                            <i class="bi bi-chevron-bar-right"></i>
                        </button>
                    </div>
                </div>
            </div>
            <!-- 信息面板 -->
            <div class="col-md-4 info-panel-col" id="infoPanelCol">
                <div class="resize-handle" id="resizeHandle"></div>
                <div class="method-panel">
                    <button class="btn btn-sm btn-secondary toggle-panel-btn" id="togglePanel">
                        <i class="bi bi-x-lg"></i>
                    </button>
                    <h4 style="margin-top: 40px">&lt;method name&gt;</h4>
                    <div id="customMessage">
                        &lt;Custom message&gt;
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加 Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script type="module" src="/static/util.js"></script>
    <script type="module" src="/static/client.js"></script>
    <script type="module">
        import { KotoneDebugClient } from '/static/client.js';
        import { render, loadComponent, debounce } from '/static/util.js';
        loadComponent('/static/kbd-color.html');
        
        $(document).ready(function() {
            let currentScale = 1.0;
            const ZOOM_STEP = 0.1;
            const MIN_SCALE = 0.1;
            const MAX_SCALE = 5.0;
            let isDragging = false;
            let startX, startY;
            let translateX = 0, translateY = 0;
            let funcHistory = []; // 服务器推送的函数执行结果
            let currentFuncIndex = -1;
            let currentImageIndex = 0;  // 当前图片页码
            let isResizing = false;
            let startWidth = 0;
            let minWidth = 200;  // 最小宽度
            let maxWidth = 800;  // 最大宽度
            let isViewLocked = false;  // 视图锁定状态
            let lastScale = 1.0;  // 上一次的缩放值
            let lastTranslateX = 0;  // 上一次的X位移
            let lastTranslateY = 0;  // 上一次的Y位移
            let localImageMap = new Map();  // 本地图片映射表
            let localMode = false;  // 是否为本地模式

            // 处理本地文件夹选择
            async function handleLocalFolder() {
                try {
                    const dirHandle = await window.showDirectoryPicker();
                    
                    // 清空之前的数据
                    localImageMap.clear();
                    funcHistory = [];
                    currentFuncIndex = -1;
                    localMode = true;  // 切换到本地模式
                    
                    // 读取所有文件
                    for await (const entry of dirHandle.values()) {
                        if (entry.kind === 'file') {
                            const file = await entry.getFile();
                            
                            // 处理图片文件
                            if (file.type.startsWith('image/')) {
                                const fileName = entry.name.replace(/\.[^/.]+$/, ""); // 移除扩展名
                                const dataUrl = await readFileAsDataURL(file);
                                localImageMap.set(fileName, dataUrl);
                            }
                            
                            // 处理 JSON 文件
                            if (file.name.endsWith('.json')) {
                                const text = await file.text();
                                const lines = text.split('\n').filter(line => line.trim());
                                
                                for (const line of lines) {
                                    try {
                                        const data = JSON.parse(line);
                                        if (data.image && data.name && data.details) {
                                            funcHistory.push(data);
                                        }
                                    } catch (e) {
                                        console.error('Invalid JSON line:', line);
                                    }
                                }
                                
                                // 只处理第一个 JSON 文件
                                break;
                            }
                        }
                    }
                    
                    // 如果有数据，显示第一条记录
                    if (funcHistory.length > 0) {
                        showHistoryImage(0);
                    }
                } catch (err) {
                    // 如果是用户取消选择，直接返回
                    if (err.name === 'AbortError') {
                        return;
                    }
                    console.error('Error reading local folder:', err);
                    alert('读取文件夹失败：' + err.message);
                }
            }

            // 读取文件为 DataURL
            function readFileAsDataURL(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = reject;
                    reader.readAsDataURL(file);
                });
            }

            // 显示/隐藏连接状态
            function showConnectionStatus(show) {
                const status = $('#connectionStatus');
                if (show) {
                    status.addClass('show');
                } else {
                    status.removeClass('show');
                }
            }

            // 更新图片计数
            function updateImageCount() {
                $('#funcCount').text(`${currentFuncIndex + 1}/${funcHistory.length}`);
                $('#firstBtn').prop('disabled', currentFuncIndex <= 0);
                $('#prevBtn').prop('disabled', currentFuncIndex <= 0);
                $('#nextBtn').prop('disabled', currentFuncIndex >= funcHistory.length - 1);
                $('#lastBtn').prop('disabled', currentFuncIndex >= funcHistory.length - 1);
                
                // 更新滑块最大值
                const slider = $('#pageSlider');
                slider.attr('max', Math.max(0, funcHistory.length - 1));
            }

            // 显示历史图片
            function showHistoryImage(index) {
                if (index < 0 || index >= funcHistory.length) return;
                currentFuncIndex = index;
                const imageData = funcHistory[index];
                
                // 重置当前图片页码
                currentImageIndex = 0;
                showCurrentImage();
                
                // 更新标题和详情
                $('h4').text(imageData.name);
                $('#customMessage').html(render(imageData.details, (key) => {
                    // 根据模式选择图片来源
                    if (localMode && localImageMap.has(key)) {
                        return localImageMap.get(key);
                    }
                    return '/api/read_memory?key=' + key;
                }));
                
                // 更新计数和滑块
                updateImageCount();
                $('#pageSlider').val(currentFuncIndex);
            }

            // 显示当前结果中的指定页码图片
            function showCurrentImage() {
                if (currentFuncIndex < 0) return;
                
                const imageData = funcHistory[currentFuncIndex].image;
                const imageValues = imageData;

                // 更新图片
                const imageContainer = $('#imageViewer');
                const img = $('<img>');
                
                // 根据模式和图片类型设置图片 URL
                const imgValue = imageValues.value[currentImageIndex];
                if (localMode && localImageMap.has(imgValue)) {
                    img.attr('src', localImageMap.get(imgValue));
                } else if (imageData.type === 'memory') {
                    img.attr('src', `/api/read_memory?key=${imgValue}`);
                } else if (imageData.type === 'file') {
                    img.attr('src', `/api/read_file?path=${imgValue}`);
                }
                
                imageContainer.empty().append(img);
                
                // 根据锁定状态决定是否保持视图
                if (isViewLocked) {
                    currentScale = lastScale;
                    translateX = lastTranslateX;
                    translateY = lastTranslateY;
                    updateImageTransform(img, false);  // 移除动画效果
                } else {
                    // 重置位移
                    translateX = 0;
                    translateY = 0;
                    // 图片加载完成后调整缩放以适应容器
                    img.on('load', function() {
                        const container = imageContainer;
                        const containerRatio = container.width() / container.height();
                        const imageRatio = this.width / this.height;
                        
                        if (imageRatio > containerRatio) {
                            currentScale = container.width() / this.width * 0.9;
                        } else {
                            currentScale = container.height() / this.height * 0.9;
                        }
                        updateImageTransform(img, false);  // 移除动画效果
                        updateZoomLevel();
                    });
                }
                
                // 应用当前的缩放和位移
                updateImageTransform(img, false);  // 移除动画效果
                updateZoomLevel();
                
                // 初始化拖拽事件
                initDragEvents();
                
                // 更新图片页码显示和按钮状态
                updateImagePageCount();
            }

            // 更新图片页码显示
            function updateImagePageCount() {
                if (currentFuncIndex < 0) return;
                
                const imageData = funcHistory[currentFuncIndex].image.value;
                
                $('#imagePageCount').text(`${currentImageIndex + 1}/${imageData.length}`);
                $('#prevImageBtn').prop('disabled', currentImageIndex <= 0);
                $('#nextImageBtn').prop('disabled', currentImageIndex >= imageData.length - 1);
            }

            // 更新缩放级别显示
            function updateZoomLevel() {
                $('#zoomLevel').text(Math.round(currentScale * 100) + '%');
            }

            // 更新图片变换
            function updateImageTransform(img, useAnimation = false) {
                requestAnimationFrame(() => {
                    if (useAnimation) {
                        img.addClass('with-animation');
                    } else {
                        img.removeClass('with-animation');
                    }
                    
                    img.css('transform', `translate(${translateX}px, ${translateY}px) scale(${currentScale})`);
                    
                    // 如果使用了动画，等动画结束后移除动画类
                    if (useAnimation) {
                        debounce(() => {
                            img.removeClass('with-animation');
                        }, 200); // 与 CSS 中的动画时间相匹配
                    }
                    
                    // 保存当前视图状态
                    lastScale = currentScale;
                    lastTranslateX = translateX;
                    lastTranslateY = translateY;
                });
            }

            // 设置图片缩放
            function setImageScale(scale, useAnimation = false) {
                currentScale = Math.min(Math.max(scale, MIN_SCALE), MAX_SCALE);
                const img = $('#imageViewer img');
                updateImageTransform(img, useAnimation);
                updateZoomLevel();
            }

            // 初始化拖拽事件
            function initDragEvents() {
                const container = $('#imageViewer');
                const img = container.find('img');

                img.on('mousedown', function(e) {
                    isDragging = true;
                    startX = e.clientX - translateX;
                    startY = e.clientY - translateY;
                    img.addClass('dragging');
                });

                $(document).on('mousemove', function(e) {
                    if (!isDragging) return;
                    translateX = e.clientX - startX;
                    translateY = e.clientY - startY;
                    updateImageTransform(img);
                });

                $(document).on('mouseup', function() {
                    if (!isDragging) return;
                    isDragging = false;
                    img.removeClass('dragging');
                });

                // 防止拖拽时选中文本
                container.on('dragstart', function(e) {
                    e.preventDefault();
                });
            }

            // 缩放按钮事件（手动缩放，使用动画）
            $('#zoomInBtn').click(() => setImageScale(currentScale + ZOOM_STEP, true));
            $('#zoomOutBtn').click(() => setImageScale(currentScale - ZOOM_STEP, true));
            $('#resetZoomBtn').click(() => setImageScale(1.0, true));

            // 鼠标滚轮缩放（手动缩放，使用动画）
            $('#imageViewer').on('wheel', function(e) {
                e.preventDefault();
                const delta = e.originalEvent.deltaY;
                setImageScale(currentScale + (delta > 0 ? -ZOOM_STEP : ZOOM_STEP), true);
            });

            // 面板切换
            $('#togglePanel').click(function() {
                const infoPanel = $('#infoPanelCol');
                const imageViewer = $('#imageViewerCol');
                const expandBtn = $('#expandPanel');

                if (infoPanel.is(':visible')) {
                    infoPanel.hide();
                    imageViewer.removeClass('col').addClass('col-12');
                    expandBtn.show();
                }
            });

            $('#expandPanel').click(function() {
                const infoPanel = $('#infoPanelCol');
                const imageViewer = $('#imageViewerCol');
                $(this).hide();

                imageViewer.removeClass('col-12').addClass('col');
                infoPanel.show();
            });

            // 导航按钮事件
            $('#firstBtn').click(() => showHistoryImage(0));
            $('#prevBtn').click(() => showHistoryImage(currentFuncIndex - 1));
            $('#nextBtn').click(() => showHistoryImage(currentFuncIndex + 1));
            $('#lastBtn').click(() => showHistoryImage(funcHistory.length - 1));

            // 初始化拖拽调整宽度
            function initResizeHandle() {
                const handle = $('#resizeHandle');
                const panel = $('#infoPanelCol');
                
                handle.on('mousedown', function(e) {
                    isResizing = true;
                    startWidth = panel.width();
                    startX = e.clientX;
                    handle.addClass('dragging');
                    e.preventDefault();
                });
                
                $(document).on('mousemove', function(e) {
                    if (!isResizing) return;
                    
                    const delta = startX - e.clientX;
                    let newWidth = startWidth + delta;
                    
                    // 限制最小和最大宽度
                    newWidth = Math.max(minWidth, Math.min(maxWidth, newWidth));
                    
                    // 更新面板宽度
                    panel.css('width', newWidth + 'px');
                    panel.css('flex', 'none');  // 防止 flex 布局影响宽度
                });
                
                $(document).on('mouseup', function() {
                    if (!isResizing) return;
                    isResizing = false;
                    handle.removeClass('dragging');
                });
            }

            // 下载当前图片组
            function downloadCurrentImage() {
                if (currentFuncIndex < 0 || currentFuncIndex >= funcHistory.length) return;
                const imageData = funcHistory[currentFuncIndex].image;
                
                // 生成基础文件名
                const name = funcHistory[currentFuncIndex].name;
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                
                // 下载所有图片
                imageData.value.forEach((val, index) => {
                    const link = document.createElement('a');
                    if (localMode && localImageMap.has(val)) {
                        link.href = localImageMap.get(val);
                    } else if (imageData.type === 'memory') {
                        link.href = `/api/read_memory?key=${val}`;
                    } else {
                        link.href = `/api/read_file?path=${val}`;
                    }
                    
                    // 如果只有一张图片，不添加索引
                    const fileName = imageData.length > 1 
                        ? `${name}_${index + 1}_${timestamp}.png`
                        : `${name}_${timestamp}.png`;
                    
                    link.download = fileName;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                });
            }

            // 键盘控制
            $(document).keydown(function(e) {
                // 如果正在输入，不处理键盘事件
                if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
                
                switch(e.key) {
                    case 'ArrowLeft':
                        if (!$('#prevBtn').prop('disabled')) {
                            showHistoryImage(currentFuncIndex - 1);
                        }
                        break;
                    case 'ArrowRight':
                        if (!$('#nextBtn').prop('disabled')) {
                            showHistoryImage(currentFuncIndex + 1);
                        }
                        break;
                    case 'Home':
                        if (!$('#firstBtn').prop('disabled')) {
                            showHistoryImage(0);
                        }
                        break;
                    case 'End':
                        if (!$('#lastBtn').prop('disabled')) {
                            showHistoryImage(funcHistory.length - 1);
                        }
                        break;
                }
            });

            // 下载按钮事件
            $('#downloadBtn').click(downloadCurrentImage);

            // 清除所有数据
            function clear() {
                funcHistory = [];
                currentFuncIndex = -1;
                currentImageIndex = 0;
                localImageMap.clear();
                localMode = false;
                
                // 清除图片显示
                $('#imageViewer').empty();
                
                // 重置标题和详情
                $('h4').text('<method name>');
                $('#customMessage').html('<Custom message>');
                
                // 更新计数和滑块
                updateImageCount();
                $('#pageSlider').val(0);
                
                // 更新图片页码显示
                updateImagePageCount();
            }

            // 初始化所有功能
            function initializeUI() {
                const client = new KotoneDebugClient(window.location.host);
                
                // 监听连接状态
                client.addEventListener('connectionStatus', (e) => {
                    showConnectionStatus(!e.connected);
                    if (e.connected) {
                        // 连接恢复时清除数据
                        clear();
                    }
                });
                
                // 监听可视化事件
                client.addEventListener('visual', (e) => {
                    if (localMode) return;  // 本地模式下不接收服务器事件
                    
                    // 访问接收到的图片，让浏览器立刻在本地缓存图片，
                    // 避免之后服务器被异常阻塞的时候，无法显示图片
                    const imageData = e.data.image;
                    if (imageData && imageData.value) {
                        imageData.value.forEach(val => {
                            const imgUrl = imageData.type === 'memory' 
                                ? `/api/read_memory?key=${val}`
                                : `/api/read_file?path=${val}`;
                            fetch(imgUrl).catch(err => console.warn('Failed to preload image:', err));
                        });
                    }
                    
                    funcHistory.push(e.data);
                    // 只有当前正在查看最后一张图片时，才自动显示新图片
                    if (currentFuncIndex === funcHistory.length - 2 || currentFuncIndex === -1) {
                        currentFuncIndex = funcHistory.length - 1;
                        showHistoryImage(currentFuncIndex);
                    } else {
                        // 否则只更新计数和按钮状态
                        updateImageCount();
                    }
                });

                // 添加本地文件夹打开按钮事件
                $('#openLocalBtn').click(handleLocalFolder);
                
                // 添加清除按钮事件
                $('#clearBtn').click(clear);
                
                initResizeHandle();
                
                // 初始化滑块事件
                $('#pageSlider').on('input', function() {
                    showHistoryImage(parseInt($(this).val()));
                });
                
                // 初始化锁定视图复选框事件
                $('#lockViewCheckbox').on('change', function() {
                    isViewLocked = $(this).prop('checked');
                });
                
                // 初始化图片分页按钮事件
                $('#prevImageBtn').click(function() {
                    if (currentImageIndex > 0) {
                        currentImageIndex--;
                        showCurrentImage();
                    }
                });
                
                $('#nextImageBtn').click(function() {
                    const func = funcHistory[currentFuncIndex];
                    if (currentImageIndex < func.image.value.length - 1) {
                        currentImageIndex++;
                        showCurrentImage();
                    }
                });
            }

            // 修改初始化调用
            initializeUI();
        });
    </script>
</body>
</html>
